package com.googlecode.recycled.lang.jse.lang;

import com.googlecode.recycled.lang.assertions.Assert;
import org.apache.commons.lang.UnhandledException;

import javax.annotation.Nullable;
import java.lang.reflect.Field;

public class Reflections {

    protected Reflections() {
    }

    public static <T> T getField(Object target, String fieldName) {
        Assert.notNull(target);
        Assert.notBlank(fieldName);

        try {
            Field field = target.getClass().getDeclaredField(fieldName);
            Assert.notNull(field);
            field.setAccessible(true);
            return (T) field.get(target);
        } catch (IllegalAccessException e) {
            throw new UnhandledException(e);
        } catch (NoSuchFieldException e) {
            throw new UnhandledException(e);
        }
    }

    public static void setField(Object target, String fieldName, @Nullable Object value) {
        Assert.notNull(target);
        Assert.notBlank(fieldName);

        try {
            Field field = target.getClass().getDeclaredField(fieldName);
            Assert.notNull(field);
            field.setAccessible(true);
            field.set(target, value);
        } catch (IllegalAccessException e) {
            throw new UnhandledException(e);
        } catch (NoSuchFieldException e) {
            throw new UnhandledException(e);
        }
    }

}
